import 'dart:async';
import 'package:baseProjectFlutter/utils/lifecycle/lifecycle.dart';

typedef Observer<T> = void Function(T value);

class LiveData<T> {
  /// 最新的值
  T? _value;

  //是否可以通知
  bool Function(T)? canCall;

  /// StreamController.broadcast() 允许有多个订阅者同时监听同一个 Stream。如果你的应用场景只需要单个订阅者，可以使用默认的 StreamController 构造函数。
  final StreamController<T> _controller;

  /// 事件总线流的控制器。
  StreamController get streamController => _controller;
  final Map<Observer<T>, StreamSubscription<T>> _streamSubscription = {};
  final Map<Observer<T>, ObserverWrapper> _observers = {};

  /// 创建EventBus。
  /// 如果sync为真，则事件将在火警呼叫期间直接传递给流的侦听器。如果为false（默认值），则事件将在稍后创建事件的代码完成后传递给侦听器
  LiveData({bool sync = false}) : _controller = StreamController.broadcast(sync: sync);

  T? get value => _value;

  /// 添加数据到 Stream
  void post(T value) {
    if (!_controller.isClosed) {
      _value = value;
      _controller.sink.add(value);
    }
  }

  /// 关闭 Stream
  void dispose() {
    _observers.clear();
    _streamSubscription.forEach((key, value) {
      value.cancel();
    });
    _streamSubscription.clear();
    _controller.close();
  }

  /// 获取 Stream
  Stream<T> get _stream => _controller.stream;

  void removeObserver(Observer<T> observer) {
    _observers.remove(observer)?.detachObserver();
    _streamSubscription.remove(observer)?.cancel();
  }

  ///自适应生命周期
  StreamSubscription<T> observe(LifecycleOwner owner, Observer<T> observer) {
    // LogUtils.e("observe ${owner.runtimeType},,${owner.hashCode}");
    //去除之前的监听
    removeObserver(observer);
    final wrapper = _LifecycleBoundObserver<T>(this, owner, observer);
    owner.addObserver(wrapper);
    _observers[observer] = wrapper;
    //监听
    StreamSubscription<T> streamSubscription = _stream.listen((event) {
      if (canCall?.call(event) != false) {
        observer(event);
      }
    });

    /// 保存对象方便调用
    _streamSubscription[observer] = streamSubscription;
    return streamSubscription;
  }

  //永居订阅
  StreamSubscription<T> observeForever(Observer<T> observer) {
    //去除之前的监听
    removeObserver(observer);
    //监听
    StreamSubscription<T> streamSubscription = _stream.listen((event) {
      if (canCall?.call(event) != false) {
        observer(event);
      }
    });

    /// 保存对象方便调用
    _streamSubscription[observer] = streamSubscription;
    return streamSubscription;
  }
}

abstract class ObserverWrapper {
  void detachObserver();
}

class _LifecycleBoundObserver<T> extends LifecycleObserver implements ObserverWrapper {
  final LiveData<T> liveData;
  final LifecycleOwner owner;
  final Observer<T> observer;

  _LifecycleBoundObserver(this.liveData, this.owner, this.observer);

  @override
  void onDispose() {
    super.onDispose();

    ///销毁，之前去除LiveData监听
    liveData.removeObserver(observer);
  }

  @override
  void detachObserver() {
    owner.removeObserver(this);
  }
}
